# words/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Noun, Verb, Adjective, Other, Synset, Term, VerbConjugation
import logging
from .serializers import SynonymResponseSerializer
import base64
from django.http import HttpResponse
import requests
logger = logging.getLogger(__name__)

class WordDetailAPIView(APIView):
    def get(self, request, word, format=None):
        word = word.lower()
        data = {}
        logger.debug(f"Received request to search for word: {word}")

        # 尝试在主词类表中查找
        noun = Noun.objects.filter(word__iexact=word).first()
        if noun:
            data['noun'] = {
                'word': noun.word,
                'sentence': noun.sentence.split('#'),
                'chinese': noun.chinese,
                'chinese_sentence': noun.chinese_sentence.split('#'),
                'level': noun.level,
                'm': noun.m,
                'gender': noun.gender.split('#'),
                'plurals': noun.plurals
            }
            logger.debug(f"Noun found: {noun.word}")

        verb = Verb.objects.filter(word__iexact=word).first()
        if verb:
            conjugations = verb.conjugations.all()
            conjugations_data = {
                'present': [],
                'past': []
            }
            for conj in conjugations:
                if conj.form_type == 'present':
                    conjugations_data['present'].append({
                        'person': conj.get_person_display(),
                        'form': conj.conjugated_form
                    })
                elif conj.form_type == 'past':
                    conjugations_data['past'].append({
                        'person': conj.get_person_display(),
                        'form': conj.conjugated_form
                    })

            data['verb'] = {
                'word': verb.word,
                'sentence': verb.sentence.split('#'),
                'chinese': verb.chinese,
                'chinese_sentence': verb.chinese_sentence.split('#'),
                'level': verb.level,
                'stark': verb.stark,
                'divisible': verb.divisible,
                'reflexive': verb.reflexive,
                'auxiliary': verb.auxiliary,
                'p1': verb.p1,
                'p2': verb.p2,
                'conjugations': conjugations_data,
                'base_form': verb.word  # 假设 base_form 就是 word
            }
            logger.debug(f"Verb found: {verb.word}")

        adjective = Adjective.objects.filter(word__iexact=word).first()
        if adjective:
            data['adjective'] = {
                'word': adjective.word,
                'sentence': adjective.sentence.split('#'),
                'chinese': adjective.chinese,
                'chinese_sentence': adjective.chinese_sentence.split('#'),
                'level': adjective.level
            }
            logger.debug(f"Adjective found: {adjective.word}")

        other = Other.objects.filter(word__iexact=word).first()
        if other:
            data['other'] = {
                'word': other.word,
                'sentence': other.sentence.split('#'),
                'chinese': other.chinese,
                'chinese_sentence': other.chinese_sentence.split('#'),
                'level': other.level
            }
            logger.debug(f"Other found: {other.word}")

        # 查询同义词


        # 如果主词类表中未找到，尝试动词变位反向查找
        if not data:
            conjugation = VerbConjugation.objects.filter(conjugated_form__iexact=word).first()
            if conjugation:
                base_verb = conjugation.verb
                conjugations = base_verb.conjugations.all()
                conjugations_data = {
                    'present': [],
                    'past': []
                }
                for conj in conjugations:
                    if conj.form_type == 'present':
                        conjugations_data['present'].append({
                            'person': conj.get_person_display(),
                            'form': conj.conjugated_form
                        })
                    elif conj.form_type == 'past':
                        conjugations_data['past'].append({
                            'person': conj.get_person_display(),
                            'form': conj.conjugated_form
                        })

                data['verb'] = {
                    'word': base_verb.word,
                    'sentence': base_verb.sentence.split('#'),
                    'chinese': base_verb.chinese,
                    'chinese_sentence': base_verb.chinese_sentence.split('#'),
                    'level': base_verb.level,
                    'stark': base_verb.stark,
                    'divisible': base_verb.divisible,
                    'reflexive': base_verb.reflexive,
                    'auxiliary': base_verb.auxiliary,
                    'p1': base_verb.p1,
                    'p2': base_verb.p2,
                    'conjugations': conjugations_data,
                    'base_form': base_verb.word
                }
                logger.debug(f"Base verb found via conjugation: {base_verb.word}")


        return Response(data, status=status.HTTP_200_OK)

class WordSynonymAPIView(APIView):
    def get(self, request, word, format=None):
        """
        根据输入的单词，查询其同义词，并将其分为单词和短语两部分返回。
        """
        word = word.strip()
        if not word:
            logger.error("缺少参数: word")
            return Response({'error': '缺少参数: word'}, status=status.HTTP_400_BAD_REQUEST)

        logger.debug(f"正在查询同义词的单词: {word}")

        # 查找包含该单词的 synset
        synsets = Synset.objects.filter(
            is_visible=True,
            term__word__iexact=word  # 确保不区分大小写
        ).distinct()

        if not synsets.exists():
            logger.warning(f"未找到单词的同义词: {word}")
            return Response({'message': '未找到相关同义词。'}, status=status.HTTP_404_NOT_FOUND)

        synonyms = set()
        phrases = set()

        for synset in synsets:
            # 获取同一个 synset 下的所有词，排除输入的单词
            related_terms = Term.objects.filter(
                synset=synset
            ).exclude(word__iexact=word)

            for related in related_terms:
                # 判断是单词还是短语
                if ' ' in related.word or '(' in related.word or ')' in related.word:
                    phrases.add(related.word)
                else:
                    synonyms.add(related.word)

        # 转换为列表并排序
        synonyms_list = sorted(list(synonyms))
        phrases_list = sorted(list(phrases))

        # 构建响应数据
        response_data = {
            'lemma': word,
            'synonyms': synonyms_list,
            'phrases': phrases_list
        }

        logger.debug(f"同义词结果: {response_data}")

        serializer = SynonymResponseSerializer(response_data)
        return Response(serializer.data, status=status.HTTP_200_OK)

class PronunciationView(APIView):
    def get(self, request, word, format=None):
        try:
            encoded_word = self.encode_word(word)
            audio_url = f"https://api.frdic.com/api/v2/speech/speakweb?langid=de&txt={encoded_word}"
            audio_response = requests.get(audio_url, timeout=10)
            audio_response.raise_for_status()
            # 假设返回的是MP3格式
            return HttpResponse(audio_response.content, content_type='audio/mpeg')
        except requests.RequestException as e:
            logger.error(f"音频请求错误: {e}")
            return Response({"error": "获取音频失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def encode_word(self, word):
        """
        按照音频API的要求对单词进行编码
        """
        number_str = str(word)
        base64_bytes = base64.b64encode(number_str.encode('utf-8'))
        base64_str = base64_bytes.decode('utf-8')
        encoded_str = base64_str.replace('=', '%3D')
        return "QYN" + encoded_str
